package com.imooc.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imooc.domain.MiaoshaOrder;
import com.imooc.domain.MiaoshaUser;
import com.imooc.redis.RedisService;
import com.imooc.service.GoodsService;
import com.imooc.service.MiaoshaService;
import com.imooc.service.OrderService;
import com.imooc.vo.GoodsVo;

@Service
public class MqReceiver {
	
	private static Logger log = LoggerFactory.getLogger(MqReceiver.class);
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	MiaoshaService miaoshaService;
	
	
	@RabbitListener(queues=MqConfig.MIAOSHA_QUEUE)
	public void receiverMiaosha(String message){
		log.info("receiver message:" + message);
		MiaoshaMessage mm = RedisService.stringToBean(message, MiaoshaMessage.class);
		MiaoshaUser user = mm.getUser();
		long goodsId = mm.getGoodsId();
	
		// 判断库存
		GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);
		String stock = goods.getGoodsStock();
		if(Integer.valueOf(stock) <= 0){
			return;
		}
		// 判断是否已经秒杀到了
		MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdAndGoodsId(user.getId(), goodsId);
		if(order != null){
			return;
		}
		// 减库存下订单，写入秒杀订单
		miaoshaService.miaosha(user, goods);
		
	}
	
	@RabbitListener(queues=MqConfig.QUEUE)
	public void receiver(String message){
		log.info("receiver message:" + message);
	}

	@RabbitListener(queues=MqConfig.TOPIC_QUEUE1)
	public void receiveTopic1(String message){
		log.info("=====topic queue1 message:{}", message);
	}
	
	@RabbitListener(queues=MqConfig.TOPIC_QUEUE2)
	public void receiveTopic2(String message){
		log.info("=====topic queue2 message:{}", message);
	}
	
	@RabbitListener(queues=MqConfig.HEADER_QUEUE)
	public void receiveHeader(byte[] message){
		log.info("=====header queue message:{}", message);
	}
	
}
